<template>
  <NewCard title="收银台" isright="isright">
    <template slot="right">
      <span class="hintRight">请在 <DownTime :time="timestamp"></DownTime> 内完成支付，超时自动关闭订单</span>
    </template>
    <div class="pay">
      <div class="pay_main">
        <el-card shadow="never">
          <h3>{{ goodsList.title || currentDetail.name }}</h3>
          <p>发送格式: PDF</p>
          <p>应付问金：{{ goodsList.amount | sumFilters }}</p>
        </el-card>
        <el-row v-if="isEmailOrDown">
          <el-col :sm="24" :lg="12">
            <p class="inputTitle">
              电邮 <span>(将本内容以PDF的形式分享至对方邮箱)</span>
            </p>
            <el-input
              v-model="email"
              placeholder="请输入对方邮箱"
              @blur="rulEmail(email)"
            ></el-input>
          </el-col>
        </el-row>
        <el-row v-if="!isEmailOrDown">
          <el-col :span="12">
            <p class="inputTitle">接收信息</p>
            <el-input
              v-model="acceptEmail"
              placeholder="请输入邮箱"
              @blur="rulEmail(acceptEmail)"
            >
            </el-input>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <Compay
              ref="compay"
              :orderinfo="orderinfo"
              :email="acceptEmail"
            ></Compay>
          </el-col>
        </el-row>
      </div>
      <div class="payBtn" v-show="btnpay">
        <p>
          应付问金：<span>{{ goodsList.amount | sumFilters }}</span>
        </p>
        <el-button round @click="payBtn">立即支付</el-button>
      </div>
    </div>
  </NewCard>
</template>

<script>
import NewCard from "@/wss/components/newCard.vue";
import Compay from "@/BMViews/components/Compay/index.vue";
import {
  getDocMailEmailApi,
  getOverallDownloadPdfApi,
} from "@/BMViews/api/doc/mail.js";
import { getDepositVoucherPayApi } from "@/BMViews/api/financial/deposit.js";
import { addDocTopEmailApi } from "@/BMViews/api/doc/top.js";
import { downloadfun } from "@/wss/utils/wss.js";
import debounce from "lodash/debounce";
import DownTime from "@/components/downTime/index.vue"
export default {
  name: "Pay",
  components: { NewCard, Compay, DownTime },
  // props:['currentDetail','goodsList'],
  props: {
    //当前文章的数据
    currentDetail: {
      type: Object,
      default: () => {
        return {};
      },
    },
    //当前订单是否支付返回的订单信息
    goodsList: {
      type: Object,
      default: () => {
        return {};
      },
    },
    //判断是点击的是电邮还是下载文档
    isEmailOrDown: {
      type: Boolean,
      default: () => {
        return {};
      },
    },
    //判断当前是推荐页面还是内容详情页面
    isFeat: {
      type: Boolean,
      default: false,
    },
    //搜索内容详情页传过来的esType
    listActive: {
      type: String,
    },
  },
  data() {
    return {
      isright: true, //显示时间提示支付
      email: "", //电邮
      acceptEmail: "", //接收邮箱
      activeName: "askGold", //默认显示问金支付
      circleUrl:
        "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png", //头像
      askRadio: "2",

      btnpay: true, //扫码支付就隐藏立即支付
      minutes: 15, //分
      seconds: 0, //，秒
      //订单信息
      orderinfo: {
        id: "",
      },

      timestamp: 0,//时间戳
    };
  },
  mounted() {
    // 拿到默认绑定的邮箱
    this.acceptEmail = this.$store.state.user.email;
    this.email = this.$store.state.user.email;

    // 获取订单的id
    this.orderinfo.id = this.goodsList.order;
    // 合并订单的信息
    this.orderinfo = Object.assign(this.orderinfo, this.goodsList);
    // console.log(this.orderinfo);
    // this.countdown(); //倒计时
    // 获取时间戳 --------------------------------
    let nowDate = new Date()
    let date = this.goodsList.createTime
    console.log(date,'------------sssssssssssssssssss');
    this.timestamp = date + 60*1000*15 - nowDate.getTime()
    // 获取时间戳 --------------------------------end

    this.$bus.$on("hidePayBtn", this.handleClick);
    

    // 二维码支付成功之后显示回推荐页面
    // this.$bus.$on("EventPaymentCompletion", () => {
    //   if (this.isFeat) {
    //     this.$bus.$emit("featHandlerShow", 1); // 当前是推荐的页面
    //   } else {
    //     this.$bus.$emit("handlerShow", 2); // 当前是搜索的页面
    //   }
    // });

    // 支付时间到跳转回推荐页
    // this.$bus.$on('CountdownOff',()=>{
    //   if (this.isFeat) {
    //     this.$bus.$emit("featHandlerShow", 1); // 当前是推荐的页面
    //   } else {
    //     this.$bus.$emit("handlerShow", 2); // 当前是搜索的页面
    //   }
    // })
  },
  watch: {
    // 获取订单的id
    goodsList(newValue, oldValue) {
      this.orderinfo.id = this.goodsList.order;
      this.orderinfo = Object.assign(this.orderinfo, this.goodsList);

      // 获取时间戳 --------------------------------
      let nowDate = new Date()
      let date = this.goodsList.createTime
      console.log(date,'------------sssssssssssssssssss');
      this.timestamp = date + 60*1000*15 - nowDate.getTime()
      // 获取时间戳 --------------------------------end
    },
  },
  methods: {
    // 如果是扫码支付就隐藏立即支付
    handleClick(tab) {
      if (tab == "scanQr") {
        this.btnpay = false;
      } else {
        this.btnpay = true;
      }
    },

    // *******************电邮*******************
    // 邮箱的验证
    rulEmail(email) {
      let reg =
        /^[A-Za-z0-9_\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
      if (email == "") {
        this.$message({ type: "warning", message: "邮箱不能为空！" });
      } else {
        if (!reg.test(email)) {
          this.$message({ type: "warning", message: "请输入有效的邮箱！" });
        }
      }
    },

    // 问金支付
    payBtn: debounce(function () {
      // 当前是点击的电邮，还是点击的是下载文档
      if (this.isEmailOrDown) {
        // 当前是点击的电邮
        if (this.email == "") {
          this.$message({ type: "warning", message: "邮箱不能为空！" });
        } else {
          //邮箱验证
          let reg =
            /^[A-Za-z0-9_\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
          if (!reg.test(this.email)) {
            this.$message({ type: "warning", message: "请输入有效的邮箱！" });
          } else {
            this.askGoldPay(); //支付回调
          }
        }
      } else {
        // 点击的是下载文档
        if (this.acceptEmail == "") {
          this.$message({ type: "warning", message: "邮箱不能为空！" });
        } else {
          //邮箱验证
          let reg =
            /^[A-Za-z0-9_\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
          if (!reg.test(this.acceptEmail)) {
            this.$message({ type: "warning", message: "请输入有效的邮箱！" });
          } else {
            this.askGoldPay(); //支付回调
          }
        }
      }
    }, 500),

    // 支付回调
    async askGoldPay() {
     
      let circleId = this.$refs.compay.getCirecleDefaultPay();
      let { code, msg } = await getDepositVoucherPayApi({
        circleId,
        orderId: this.orderinfo.id,
        email: this.acceptEmail,
      });
      if (code != 200) return;
      this.$message({ message: "支付成功！", type: "success" });

      // 判断当前点击的是true电邮还是false下载文档
      if (this.isEmailOrDown) {
        // 如果是推荐页的显示推荐页，是内容详情的显示内容
        if (this.isFeat) {
          this.getDocMailEmail(); 
          this.$emit("completePay")
        } else {
          this.getDocMailEmail(); 
          this.$emit("completePay")
          this.$bus.$emit("collectHandlerShow", 2); //显示内容详情 我的收藏那里用的
        }
      } else {
        // 如果是推荐页的显示推荐页，是内容详情的显示内容
        if (this.isFeat) {
          // 判断当时是不是ios设备
          if(!['ios','android'].includes(this.$isDevice)){
            // console.log("是这里不");
            this.$message({ type: "success", message: "正在下载，请稍等！" });
            // 不是ios设备
            this.getOverallDownloadPdf(); //下载文档的接口
          }else{
            this.$message({ type: "success", message: "正在下载，请稍等！" });
            // 是ios设备
            this.getOverallDownloadPdfIos() //Ios下载文档的接口
          }
          this.$bus.$emit("featHandlerShow", 1); //显示推荐页
        } else {
          // 判断当时是不是ios设备
          if(!['ios'].includes(this.$isDevice)){
            // 不是ios设备
            //  console.log("是这里不123");
            this.$message({ type: "success", message: "正在下载，请稍等！" });
            this.getOverallDownloadPdf(); //下载文档的接口
          }else{
            // 是ios设备
            this.$message({ type: "success", message: "正在下载，请稍等！" });
            this.getOverallDownloadPdfIos() //Ios下载文档的接口
          }
          this.$emit("completePay")
          this.$bus.$emit("collectHandlerShow", 2); //显示内容详情 我的收藏那里用的
        }
      }
    },

    //发送电邮接口
    async getDocMailEmail() {
      let to = this.email;
      let esId = this.currentDetail.id;
      let esType = this.currentDetail.type || this.listActive;
      let result = await getDocMailEmailApi({ to, esId, esType });
      if (result.code == 200) {
        this.$message({ message: "电邮发送成功！", type: "success" });
        //电邮数量+1
        this.addDocTopEmail();
      }
    },

    //电邮数量+1
    async addDocTopEmail() {
      let result = await addDocTopEmailApi(
        this.currentDetail.id,
        this.currentDetail.esType
      );
      console.log(result,"resultresultresultresult");
      // if (result.code == 200) {
      //   this.$message({ message: "电邮发送成功！", type: "success" });
      //   //电邮数量+1
      //   this.addDocTopEmail();
      // }
    },

    // 下载文档的接口
    async getOverallDownloadPdf() {
      let to = this.email;
      let esId = this.currentDetail.id;
      let type = this.currentDetail.type || this.listActive;
      let result = await getOverallDownloadPdfApi({ esId, type });
      if (result.code == 200) {
        // 下载文件***************
        let url = result.msg;
        let fileName = url.substring(url.lastIndexOf("/") + 1); //获取文件名称
        downloadfun(fileName, url); // 下载文件需要引入
        // 下载文件***************end
      }
    },

    // 下载文档的接口（当前是ios设备）
    async getOverallDownloadPdfIos() {
      let to = this.email;
      let esId = this.currentDetail.id;
      let type = this.currentDetail.type || this.listActive;
      let result = await getOverallDownloadPdfApi({ esId, type });
      if (result.code == 200) {
        // 下载文件***************
        let url = result.msg;
        // let fileName = url.substring(url.lastIndexOf("/") + 1); //获取文件名称
        let a = document.createElement("a");
        a.style.display = "none";
        document.body.appendChild(a);
        a.href = url;
        a.click();
        // 下载文件***************end
      }
    },

    // *******************电邮*******************  end

    //倒计时
    num(n) {
      return n < 10 ? "0" + n : "" + n;
    },
    countdown() {
      var _this = this;
      var time = window.setInterval(function () {
        if (_this.seconds === 0 && _this.minutes !== 0) {
          _this.seconds = 59;
          _this.minutes -= 1;
        } else if (_this.minutes === 0 && _this.seconds === 0) {
          _this.seconds = 0;
          window.clearInterval(time);
          _this.changes();
        } else {
          _this.seconds -= 1;
        }
      }, 1000);
    },

    //返回推荐页面
    changes() {
      this.$bus.$emit("featHandlerShow", 1);
    },
  },

  computed: {
    //计算时间
    second() {
      return this.num(this.seconds);
    },
    minute() {
      return this.num(this.minutes);
    },
  },

  watch: {
    //监听时间
    second: {
      handler(newVal) {
        this.num(newVal);
      },
    },
    minute: {
      handler(newVal) {
        this.num(newVal);
      },
    },
  },
};
</script>

<style scoped>
.hintRight {
  display: flex;
  align-items: center;
  font-size: 12px;
  color: #999;
}
::v-deep .el-card__body {
  position: relative;
}
/* 支付信息 */
.pay {
  margin-top: 15px;
  padding: 0 30px;
}
.pay_main {
  margin-bottom: 70px;
}
.pay_main .el-card {
  border-radius: 12px;
}
::v-deep .pay_main .el-card__body {
  padding: 20px !important;
}
.pay_main h3 {
  margin: 0;
  margin-bottom: 12px;
  font-size: 16px;
  color: #333;
  font-weight: bold;
}
.pay_main p {
  font-size: 14px;
  color: #999;
  margin: 0;
  line-height: 24px;
}
.pay_main .el-row {
  margin-top: 40px;
}
::v-deep .pay_main .el-row .el-input__inner {
  border-radius: 8px;
  height: 44px;
  line-height: 44px;
}
.pay_main .el-row .acceptEmail {
  border: 0;
  padding: 5px 0;
  margin: 7px 0;
  margin-right: 10px;
  font-size: 14px;
  color: #bababa;
  background: #fff;
  cursor: pointer;
}
.pay_main .el-row .acceptEmail:hover {
  color: #f87a23;
}
.pay_main .inputTitle {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin-bottom: 15px;
}
.pay_main .inputTitle span {
  font-size: 14px;
  color: #999;
  font-weight: 400;
}
::v-deep .pay_main .el-tabs__header {
  border: 0;
  margin-bottom: 24px;
}
::v-deep .pay_main .el-tabs__nav {
  width: 100%;
  display: flex;
  justify-content: space-between;
  border: 0;
}
::v-deep .pay_main .el-tabs__item {
  width: 49%;
  border-radius: 8px;
  text-align: center;
  font-size: 14px;
  font-weight: bold;
  border: 0;
  background-color: #fafafa;
}
::v-deep .pay_main .el-tabs__item.is-active {
  background-color: #f1f3ff;
  color: #39486f;
}
::v-deep .pay_main .el-tabs__item:hover {
  color: #39486f;
}

.askGold {
  list-style: none;
  padding: 0;
  margin: 0;
  width: 100%;
}
.askGold li {
  display: flex;
  margin-bottom: 24px;
}
.askGold li .el-avatar {
  margin-right: 14px;
}
.askGold .askInfo h3 {
  margin-bottom: 5px;
  font-size: 16px;
  color: #333;
}
.askGold .askInfo {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid #ecedf0;
  padding-bottom: 24px;
}
.askGold .askInfo p {
  font-size: 12px;
  color: #666;
}
.askGold .askInfo button {
  color: #39486f;
  border-color: #39486f;
  padding: 5px 15px;
}
::v-deep .askInfo .el-radio__label {
  display: none;
}
::v-deep .askInfo .el-radio .el-radio__inner {
  width: 24px;
  height: 24px;
  border-color: #bbbbbb;
  background: #fff;
}
::v-deep .askInfo .el-radio .is-disabled .el-radio__inner {
  background: #f2f2f2;
}
::v-deep .askInfo .el-radio .is-checked .el-radio__inner {
  border-color: #f87a23;
  background: #f87a23;
}
::v-deep .askInfo .el-radio__input.is-checked .el-radio__inner::after {
  content: "";
  width: 11px;
  height: 7px;
  border: 3px solid white;
  border-top: transparent;
  border-right: transparent;
  text-align: center;
  display: block;
  position: absolute;
  top: 6px;
  left: 5px;
  vertical-align: middle;
  transform: rotate(-45deg);
  border-radius: 0px;
  background: none;
}
.payBtn {
  position: absolute;
  bottom: 0;
  left: 0;
  z-index: 9;
  width: 100%;
  background-color: #fff;
  border-top: 1px solid #ecedf0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px 30px;
}
.payBtn p {
  margin: 0;
  font-size: 14px;
  font-weight: bold;
}
.payBtn p > span {
  color: #f87a23;
  font-size: 16px;
}
.payBtn .el-button {
  background-color: #f87a23;
  border-color: #f87a23;
  color: #fff;
  font-size: 14px;
  padding: 10px 50px;
}
.payBtn .el-button:hover {
  opacity: 0.9;
}

.scanQr {
  text-align: center;
}
.scanQr img {
  width: 150px;
}
.scanQr p {
  color: #f87a23;
  font-size: 18px;
  font-weight: bold;
}
.scanQr span {
  font-size: 12px;
  color: #999;
}

@media (max-width: 1120px) {
  ::v-deep .top .right {
    flex: 2;
  }
  ::v-deep .pay_main .el-card__body {
    padding: 12px 20px !important;
  }

  .pay_main .el-row {
    margin-top: 30px;
  }
  .pay_main .el-row .el-row {
    margin-top: 0px;
  }
}
</style>